<template>
  <div class="page-bg">
    <div class="container">
      <h2 class="market-title">我的 NFT</h2>
      <div v-if="loading" class="center-msg">
        <span class="loading-dot"></span> 正在加载...
      </div>
      <div v-else-if="nfts.length === 0" class="center-msg empty-card">
        <span style="font-size:2em;vertical-align:-8px;">🪪</span>
        <div>你还没有 NFT，可先去铸造。</div>
      </div>
      <div class="nft-grid">
        <div
          v-for="nft in nfts"
          :key="nft.tokenId"
          class="nft-card"
        >
          <div class="nft-img-wrap">
            <img
              :src="getNftImage(nft.tokenURI)"
              @error="e => e.target.src = 'https://placehold.co/400x400?text=NFT'"
              class="nft-img"
            />
          </div>
          <div class="nft-id">
            <span class="tag">#{{ nft.tokenId }}</span>
          </div>
          <div class="nft-uri" :title="nft.tokenURI">{{ nft.tokenURI }}</div>

          <div v-if="nft.isListed" class="nft-price" style="margin-bottom:12px;">
            <span class="tag tag-listed">已上架</span>
            <span class="eth-logo"></span>
            <span>{{ fromWei(nft.price) }}</span> ETH
          </div>
          <div v-else style="width:100%;margin-bottom:10px;">
            <form @submit.prevent="handleList(nft.tokenId)" class="list-form">
              <input
                v-model="listPrice[nft.tokenId]"
                placeholder="上架价格(ETH)"
                type="number"
                min="0"
                step="0.01"
                class="form-input list-input"
                required
                :disabled="listingId === nft.tokenId"
              />
              <button
                class="buy-btn list-btn"
                :disabled="listingId === nft.tokenId"
                type="submit"
              >
                {{ listingId === nft.tokenId ? "上架中..." : "上架" }}
              </button>
            </form>
          </div>
        </div>
      </div>
      <div v-if="errorMsg" class="tip-box tip-error">
        <span class="icon">❌</span> {{ errorMsg }}
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted } from "vue";
import { getAllListedItems, listItem } from "../utils/contract";
import { ethers } from "ethers";
import { getMyNfts } from "../utils/contract";

const nfts = ref([]);
const loading = ref(true);
const listingId = ref(0);
const listPrice = ref({});
const errorMsg = ref("");

onMounted(fetchMyNfts);

async function fetchMyNfts() {
  loading.value = true;
  errorMsg.value = "";
  nfts.value = [];
  try {
    const [address] = await window.ethereum.request({ method: 'eth_requestAccounts' });
    let items = await getMyNfts(address);
    nfts.value = Array.isArray(items) ? items : [];
  } catch (e) {
    errorMsg.value = e.data?.message || e.message || "查询失败";
  }
  loading.value = false;
}

function fromWei(wei) {
  return ethers.formatEther(wei || "0");
}
function getNftImage(tokenURI) {
  if (tokenURI && (tokenURI.endsWith(".png") || tokenURI.endsWith(".jpg") || tokenURI.endsWith(".jpeg"))) {
    return tokenURI;
  }
  return tokenURI || "https://placehold.co/400x400?text=NFT";
}

async function handleList(tokenId) {
  if (!window.ethereum) return alert("请先安装并连接钱包");
  errorMsg.value = "";
  listingId.value = tokenId;
  try {
    const priceEth = listPrice.value[tokenId];
    const priceWei = ethers.parseEther(priceEth ? priceEth.toString() : "0");
    await listItem(tokenId, priceWei);
    alert("上架成功！");
    await fetchMyNfts();
    listPrice.value[tokenId] = "";
  } catch (e) {
    errorMsg.value = e.data?.message || e.message || "上架失败";
  }
  listingId.value = 0;
}
</script>

<style scoped>
/* 公共背景色，与其他页统一 */
.page-bg {
  background: #f7f8fa;
  min-height: 100vh;
  padding: 0;
}
.container {
  max-width: 950px;
  margin: 40px auto;
  background: #fff;
  box-shadow: 0 6px 32px rgba(50,60,80,0.08);
  border-radius: 22px;
  padding: 40px 28px 30px;
}

/* 标题 */
.market-title {
  font-size: 2.3rem;
  font-weight: 700;
  color: #21344c;
  text-align: center;
  margin-bottom: 32px;
  letter-spacing: 2px;
}

/* 加载/空态 */
.center-msg {
  display: flex;
  flex-direction: column;
  align-items: center;
  color: #5e6373;
  font-size: 1.13rem;
  margin: 60px 0 36px 0;
}
.empty-card {
  background: #f0f4f9;
  border-radius: 12px;
  padding: 32px 0;
}
/* loading 点动画 */
.loading-dot {
  display: inline-block;
  width: 16px;
  height: 16px;
  border-radius: 50%;
  background: #5185e8;
  margin-right: 10px;
  animation: bounce 0.9s infinite alternate;
  vertical-align: middle;
}
@keyframes bounce {
  to { transform: translateY(-8px); opacity: .6; }
}

/* NFT 卡片区 */
.nft-grid {
  display: grid;
  grid-template-columns: 1fr;
  gap: 30px;
  margin-top: 16px;
}
@media (min-width: 700px) {
  .nft-grid {
    grid-template-columns: repeat(3, 1fr);
  }
}
.nft-card {
  background: #fafdff;
  border-radius: 16px;
  box-shadow: 0 2px 12px rgba(120,130,160,0.07);
  border: 1.5px solid #e8e9f2;
  padding: 24px 14px 18px;
  display: flex;
  flex-direction: column;
  align-items: center;
  transition: box-shadow .23s, transform .22s;
  position: relative;
}
.nft-card:hover {
  box-shadow: 0 8px 24px rgba(50,60,80,0.13);
  transform: translateY(-2px) scale(1.025);
}
/* 图片 */
.nft-img-wrap {
  border: 2.5px solid #e5e7ee;
  border-radius: 12px;
  box-shadow: 0 1.5px 8px rgba(100,110,150,0.08);
  overflow: hidden;
  margin-bottom: 16px;
  width: 154px;
  height: 154px;
  display: flex;
  align-items: center;
  justify-content: center;
  background: #f8faff;
}
.nft-img {
  width: 148px;
  height: 148px;
  object-fit: cover;
  border-radius: 8px;
  transition: transform .19s;
}
.nft-card:hover .nft-img {
  transform: scale(1.06);
}
/* NFT编号标签 */
.nft-id .tag {
  background: #e9eef6;
  color: #275aac;
  font-size: 1.07em;
  font-weight: 600;
  padding: 2px 14px 2px 11px;
  border-radius: 10px;
  letter-spacing: 1px;
  margin-bottom: 6px;
  display: inline-block;
}
/* 已上架绿色标签 */
.tag-listed {
  background: #e5faec;
  color: #23ad71;
  margin-right: 7px;
  padding: 2px 12px 2px 10px;
}
/* tokenURI 展示优化 + tooltip */
.nft-uri {
  max-width: 120px;
  overflow: hidden;
  white-space: nowrap;
  text-overflow: ellipsis;
  color: #8a97b7;
  font-size: .96em;
  margin-bottom: 8px;
  cursor: pointer;
}

/* 价格区域 */
.nft-price {
  font-size: 1.05em;
  font-weight: 600;
  color: #273e5c;
  margin-bottom: 13px;
  display: flex;
  align-items: center;
  gap: 6px;
}
.eth-logo {
  display: inline-block;
  width: 1.18em;
  height: 1.18em;
  background: url("data:image/svg+xml;utf8,<svg fill='none' viewBox='0 0 24 24' stroke='black' stroke-width='2' xmlns='http://www.w3.org/2000/svg'><path d='M12 2v20m0-20l7 12-7 4-7-4 7-12z' stroke='%235185e8'/></svg>") center/contain no-repeat;
  margin-right: 3px;
  vertical-align: -2px;
}

/* 上架表单、输入框、按钮 */
.list-form {
  display: flex;
  align-items: center;
  gap: 7px;
  width: 100%;
}
.list-input {
  flex: 1 1 0;
  min-width: 0;
}
.form-input {
  border: 1.6px solid #dde2ef;
  border-radius: 11px;
  padding: 8px 10px;
  font-size: .98em;
  outline: none;
  transition: border-color .18s, box-shadow .16s;
  background: #f9fbfe;
  color: #21344c;
  box-shadow: 0 1px 4px rgba(180,190,210,0.04);
}
.form-input:focus {
  border-color: #376ee6;
  box-shadow: 0 2px 9px rgba(90,120,200,0.08);
}
.buy-btn, .list-btn {
  background: #376ee6;
  color: #fff;
  font-size: .99em;
  font-weight: 600;
  border: none;
  border-radius: 11px;
  padding: 8px 0;
  width: 75px;
  min-width: 60px;
  box-shadow: 0 1px 3px rgba(80,120,200,0.07);
  cursor: pointer;
  transition: background .18s, box-shadow .16s, opacity .13s;
  position: relative;
  display: flex;
  justify-content: center;
  align-items: center;
}
.buy-btn:hover:enabled, .list-btn:hover:enabled {
  background: #2656ba;
}
.buy-btn:disabled, .list-btn:disabled {
  background: #b6c6e5;
  color: #ecf0fa;
  opacity: .65;
  cursor: not-allowed;
}

/* 错误提示 */
.tip-box {
  display: flex;
  align-items: center;
  gap: 7px;
  margin-top: 22px;
  border-radius: 9px;
  font-size: 1.08em;
  padding: 13px 14px;
  font-weight: 500;
  box-shadow: 0 1px 7px rgba(70,110,110,0.05);
  width: 100%;
  justify-content: center;
  word-break: break-all;
}
.tip-error {
  background: #fff3f1;
  color: #ec4141;
  border: 1.4px solid #faccca;
}
.icon {
  font-size: 1.22em;
}

@media (max-width: 600px) {
  .container {
    padding: 17px 4vw 13vw;
  }
  .nft-img-wrap { width: 100px; height: 100px;}
  .nft-img { width: 96px; height: 96px;}
  .nft-uri { max-width: 65px;}
  .market-title { font-size: 1.45rem; }
}
</style>
